package controller

import (
	beego "github.com/beego/beego/v2/server/web"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"ksd-social-api/commons/base/controller"
	"ksd-social-api/commons/global"
	utils2 "ksd-social-api/utils"
	"strconv"
	"time"
)

type WeixinNativeCoinController struct {
	controller.BaseController
	WeixinPayBaseController
}

/**
 * 微信支付 -充值
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *WeixinNativeCoinController) NativePayCoin() {
	client, ctx := web.GetWeixinPayClient()
	if nil == client {
		web.FailCodeMsg(901, "微信支付初始化失败")
		return
	}
	svc := native.NativeApiService{Client: client}
	//业务的订单编号
	OutTradeNo := web.GetSnowWorkerIdString(6)
	global.Log.Info("微信支付开始了,业务编号是：" + OutTradeNo)

	// 课程业务
	coin, _ := web.ParseParamInt("coin", 1)
	// 支付课程的金额
	payMoney := web.Yuan2FenRound(strconv.Itoa(coin))
	mchID := beego.AppConfig.DefaultString("weixin.pay.mchid", "")
	Appid := beego.AppConfig.DefaultString("weixin.pay.appid", "")
	NotifyURl := beego.AppConfig.DefaultString("weixin.pay.notifyurl", "")
	// 参数map
	mattch := map[string]any{}
	mattch["userId"] = web.GetUserId()
	mattch["type"] = "coin"
	mattch["price"] = strconv.Itoa(coin)

	// 微信产品 + 业务参数 + 开始完成微信支付
	resp, _, err := svc.Prepay(ctx,
		native.PrepayRequest{
			Appid:       core.String(Appid),
			Mchid:       core.String(mchID),
			Description: core.String("充值"),
			OutTradeNo:  core.String(OutTradeNo),
			TimeExpire:  core.Time(time.Now()),
			Attach:      core.String(utils2.MapToJson(mattch)),
			// 支付的回调地址，千万不要用程序去拦截
			NotifyUrl: core.String(NotifyURl),
			// 支付金额
			Amount: &native.Amount{
				Currency: core.String("CNY"),
				Total:    core.Int64(payMoney), // 分，必须是数字不能字符串类型数字
			},
		},
	)

	// 返回支付的产品信息
	m := map[string]any{}
	if err != nil {
		// 处理错误
		m["url"] = ""
		m["status"] = "fail"
		m["tradeNo"] = ""
	} else {
		// 处理返回结果
		m["url"] = resp.CodeUrl
		m["status"] = "success"
		m["tradeNo"] = OutTradeNo
	}

	web.Ok(m)
}

/**
 * 充值交易-查单
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *WeixinNativeCoinController) QueryOrderByCoinOutTradeNo() {
	// 获取支付的交易编号
	OutTradeNo := web.GetString("tradeno")
	client, ctx := web.GetWeixinPayClient()
	if nil == client {
		web.FailCodeMsg(901, "微信支付初始化失败")
		return
	}

	svc := native.NativeApiService{Client: client}
	// 获取商户编号
	mchID := beego.AppConfig.DefaultString("weixin.pay.mchid", "")
	// 根据交易编号查询订单
	resp, result, err := svc.QueryOrderByOutTradeNo(ctx,
		native.QueryOrderByOutTradeNoRequest{
			OutTradeNo: core.String(OutTradeNo),
			Mchid:      core.String(mchID),
		},
	)

	if err == nil {
		// 如何正常订单在支付成功了
		// result.Response.StatusCode 只是证明接口的响应是正常，就是代码没错误，不能证明支付成功了
		// *resp.TradeState=="SUCCESS" 才能证明订单是支付金额了。
		if result.Response.StatusCode == 200 && *resp.TradeState == "SUCCESS" {
			isBuyFlag := userWalletService.CountUserWalletRecordsByOutTradeNo(OutTradeNo, web.GetSystemId())
			if isBuyFlag > 0 {
				web.FailCodeMsg(902, "订单已经创建")
				return
			}
			// 这里就是解析下单的附属参数
			attchParams := AttchParams{}
			utils2.JsonToStruct(*resp.Attach, &attchParams)
			userWalletService.SaveUserWalletRecords(
				*resp.OutTradeNo, *resp.TransactionId, utils2.StructToJson(*resp), 1, "微信", attchParams.Price,
				attchParams.UserId, web.GetSystemId(), web.GetSystemName())
			web.Ok(resp)
		} else {
			web.FailCodeMsg(901, "fail")
		}
	} else {
		web.FailCodeMsg(901, "fail")
	}
}
